package com.leejxx.health.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.model.PutObjectResult;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * @Author LeeJx
 * @ClassName AliYunOssUtils
 * @Description TODO
 * @date 2021/1/3 10:00
 * @Version 1.0
 */
@Slf4j
@Data
public class AliYunOssUtils {
    //连接节点
    private String endpoint;
    private String accessKeyID;
    private String accessKeySecret;
    //存储仓库名称
    private String bucket;
    //文件夹
    private String folder;

    //创建全局客户端
    private OSS ossClient;

    //设置URL过期时间3个月
    private Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 90);

    //上传图片
    public String uploadToAliYunOSS(InputStream is, String uploadFileName) {
//        ossClient = new OSSClient(endpoint, accessKeyID, accessKeySecret);
        //新建客户端
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyID, accessKeySecret);
        URL url = null;

        try {
            //指定文件夹
            uploadFileName = folder + uploadFileName;
            //上传图片
            PutObjectResult result = ossClient.putObject(bucket, uploadFileName, is);
            log.info("[图片上传结果]result:{}", result);

            url = ossClient.generatePresignedUrl(bucket, uploadFileName, expiration);
            log.info("[图片访问路径]url:{}", url);
        } catch (OSSException | ClientException e) {
            throw new RuntimeException(e);
        } finally {
            ossClient.shutdown();
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return String.valueOf(url);
    }

    //获取图片URL
    public String getUrlFromAliYunOss(String fileName) {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyID, accessKeySecret);
        return String.valueOf(ossClient.generatePresignedUrl(bucket, fileName, expiration));
    }

    //删除图片
    public void deleteFileFromAliYunOSS(String fileName) {
//        ossClient = new OSSClient(endpoint, accessKeyID, accessKeySecret);
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyID, accessKeySecret);
        try {
            ossClient.deleteObject(bucket, fileName);
        } catch (OSSException | ClientException e) {
            throw new RuntimeException(e);
        } finally {
            ossClient.shutdown();
        }
    }
}
